<template>
  <div class="search-result">
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <van-cell v-for="(obj, ind) in list" :key="ind" :title="obj.title" />
    </van-list>
  </div>
</template>

<script>
import { getSearchResult } from '@/api/search'
export default {
  name: 'SearchResult',
  components: {},
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      page: 1,
      per_page: 10
    }
  },
  computed: {},
  watch: {},
  created () {},
  mounted () {},
  methods: {
    async onLoad () {
      // 异步更新数据
      // 1. 获取数据
      // 2. 将获取到的数据追加到数组, 实现数据更新
      // 3. 将loading 设置为 fales

      try {
        const res = await getSearchResult({
          page: this.page,
          per_page: this.per_page,
          q: this.searchText
        })
        const results = res.data.data.results
        this.list = [...this.list, ...results]
        this.loading = false
        // 4. 判断数据是否加载完毕,如果加载完毕 将finished 设置为 true
        if (results.length) {
          this.page++
        } else {
          this.finished = true
        }
      } catch (error) {
        this.loading = false
        console.log(error)
      }
    }
  }
}
</script>

<style scoped lang="less"></style>
